package com.lzy.concertticket.interceptor;

import com.lzy.concertticket.cache.FlowCache;
import com.lzy.concertticket.model.entity.FlowEntity;
import com.lzy.concertticket.model.entity.UserEntity;
import com.lzy.concertticket.threadlocal.FlowEntityThreadLocal;
import com.lzy.concertticket.threadlocal.UserEntityThreadLocal;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.BufferedReader;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Slf4j
@Component
public class FlowCountInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        FlowEntity flow = new FlowEntity();
        flow.setUri(request.getRequestURI());   //  请求资源路径
        flow.setClientIp(request.getRemoteAddr());  //  客户端ip地址
        flow.setRequestTime(LocalDateTime.now());   //  请求时间

        FlowEntityThreadLocal.set(flow);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //  获取本条流量信息
        FlowEntity flow = FlowEntityThreadLocal.get();
        flow.setResponseTime(LocalDateTime.now());  //  响应时间
        flow.setDuration(flow.getResponseTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() - flow.getRequestTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        //  设置响应码
        flow.setResponseCode(response.getStatus());

        UserEntity user = UserEntityThreadLocal.get();
        if (user != null) {
            //  记录访问人
            flow.setUserId(user.getId());
        }
        //  将流量添加至缓存
        FlowCache.addFlow(flow);
        //  从threadLocal中移除
        FlowEntityThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
